package com.qst.service.impl;

import com.qst.ExamException;
import com.qst.dao.DAOFactory;
import com.qst.dao.UserDao;
import com.qst.entity.User;
import com.qst.service.UserAdminService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserAdminServiceImpl implements UserAdminService {

    private UserDao userDao = DAOFactory.getDao(UserDao.class);

    @Override
    public List<User> findUsers() {
        List<User> userList = userDao.findAll();
        return userList;
    }

    @Override
    public User findById(int id) {
        return userDao.findById(id);
    }

    @Override
    public void deleteById(int id) {
        User user = userDao.findById(id);
        if (user == null) {
            return;
        }
        if (user.getLastLogin() != null) {
            throw new ExamException("该用户不能删除");
        }
        userDao.deleteById(id);
    }

    @Override
    public void saveUser(User user) {
        User temp = userDao.findByLogin(user.getLogin());
        if (temp != null) {
            throw new ExamException("登录名已经存在了");
        }
        userDao.insert(user);
    }

    @Override
    public void updateUser(User user) {
        User temp = userDao.findByLogin(user.getLogin());
        if (temp != null && temp.getId() != user.getId()) {
            throw new ExamException("登录名已经存在了");
        }
        userDao.update(user);
    }

    @Override
    public void resetPassword(int id) {
        userDao.updatePassword(id, User.PASSWORD);
    }
}
